package A099queue;

/**
 * SynchronousQueue没有容量。
 * <p>
 * 与其他BlockingQueue不同，SynchronousQueue是一个不存储元素的BlockingQueue。
 * <p>
 * 每一个put操作必须要等待一个take操作，否则不能继续添加元素，反之亦然。
 */

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;

public class C001_SynchronousQueue_add_remove_异常子类没有重写 {
    public static void main(String[] args) {
        BlockingQueue<String> blockingQueue = new SynchronousQueue<>();

        new Thread(() -> {
            try {
                boolean a = blockingQueue.add("A");
                System.out.println(Thread.currentThread().getName() + "\t put A =" + a);

                boolean b = blockingQueue.add("B");
                System.out.println(Thread.currentThread().getName() + "\t put B =" + b);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }, "t1").start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(() -> {
            try {
                System.out.println("检查链表长度" + blockingQueue.size());
                try {
                    TimeUnit.SECONDS.sleep(5);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                blockingQueue.remove();
                System.out.println(Thread.currentThread().getName() + "\t take A ");

                try {
                    TimeUnit.SECONDS.sleep(5);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                blockingQueue.remove();
                System.out.println(Thread.currentThread().getName() + "\t take B ");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }, "t2").start();
    }

}
